#include "sqlgenerator.h"
#include <QDateTime>
#include <QVariant>
#include <QRegExp>

/**
 * @brief 生成创建数据表的SQL语句
 * 不进行额外安全处理，仅生成基础SQL
 */
QString SqlGenerator::generateCreateTable(const QString& tableName,
                                         const QVariantMap& fields,
                                         const QString& primaryKey)
{
    if (fields.isEmpty()) {
        return "";
    }

    QString sql = QString("CREATE TABLE IF NOT EXISTS %1 (").arg(tableName);
    QStringList fieldDefinitions;

    for (auto it = fields.begin(); it != fields.end(); ++it) {
        fieldDefinitions.append(QString("%1 %2").arg(it.key()).arg(it.value().toString()));
    }

    if (!primaryKey.isEmpty() && fields.contains(primaryKey)) {
        fieldDefinitions.append(QString("PRIMARY KEY (%1)").arg(primaryKey));
    }

    sql += fieldDefinitions.join(", ") + ");";
    return sql;
}

/**
 * @brief 生成插入记录的SQL语句
 * 不进行额外安全处理，仅生成基础SQL
 */
QString SqlGenerator::generateInsert(const QString& tableName, const QVariantMap& data)
{
    if (data.isEmpty()) {
        return "";
    }

    QStringList fields;
    QStringList values;

    for (auto it = data.begin(); it != data.end(); ++it) {
        fields.append(it.key());
        // 直接转换值，不进行额外转义
        QVariant value = it.value();
        if (value.type() == QVariant::String || value.type() == QVariant::DateTime ||
            value.type() == QVariant::Date || value.type() == QVariant::Time) {
            values.append(QString("'%1'").arg(value.toString()));
        } else if (value.type() == QVariant::Bool) {
            values.append(value.toBool() ? "1" : "0");
        } else if (value.isNull()) {
            values.append("NULL");
        } else {
            values.append(value.toString());
        }
    }

    return QString("INSERT INTO %1 (%2) VALUES (%3);")
           .arg(tableName)
           .arg(fields.join(", "))
           .arg(values.join(", "));
}

/**
 * @brief 生成更新记录的SQL语句
 * 仅对WHERE条件进行安全处理
 */
QString SqlGenerator::generateUpdate(const QString& tableName,
                                    const QVariantMap& data,
                                    const QString& conditions)
{
    if (data.isEmpty()) {
        return "";
    }

    QStringList updates;
    for (auto it = data.begin(); it != data.end(); ++it) {
        QVariant value = it.value();
        QString valueStr;
        if (value.type() == QVariant::String || value.type() == QVariant::DateTime ||
            value.type() == QVariant::Date || value.type() == QVariant::Time) {
            valueStr = QString("'%1'").arg(value.toString());
        } else if (value.type() == QVariant::Bool) {
            valueStr = value.toBool() ? "1" : "0";
        } else if (value.isNull()) {
            valueStr = "NULL";
        } else {
            valueStr = value.toString();
        }
        updates.append(QString("%1 = %2").arg(it.key()).arg(valueStr));
    }

    QString sql = QString("UPDATE %1 SET %2").arg(tableName).arg(updates.join(", "));

    // 仅对条件进行安全处理
    QString sanitizedConditions = sanitizeCondition(conditions);
    if (!sanitizedConditions.isEmpty()) {
        sql += " WHERE " + sanitizedConditions;
    }

    sql += ";";
    return sql;
}

/**
 * @brief 生成删除记录的SQL语句
 * 仅对WHERE条件进行安全处理
 */
QString SqlGenerator::generateDelete(const QString& tableName, const QString& conditions)
{
    QString sql = QString("DELETE FROM %1").arg(tableName);

    // 仅对条件进行安全处理
    QString sanitizedConditions = sanitizeCondition(conditions);
    if (!sanitizedConditions.isEmpty()) {
        sql += " WHERE " + sanitizedConditions;
    }

    sql += ";";
    return sql;
}

/**
 * @brief 生成查询记录的SQL语句
 * 仅对WHERE条件进行安全处理
 */
QString SqlGenerator::generateSelect(const QString& tableName,
                                    const QStringList& fields,
                                    const QString& conditions,
                                    const QString& orderBy,
                                    int limit)
{
    QString selectFields = fields.isEmpty() ? "*" : fields.join(", ");

    QString sql = QString("SELECT %1 FROM %2").arg(selectFields, tableName);

    // 仅对条件进行安全处理
    QString sanitizedConditions = sanitizeCondition(conditions);
    if (!sanitizedConditions.isEmpty()) {
        sql += " WHERE " + sanitizedConditions;
    }

    if (!orderBy.isEmpty()) {
        sql += " ORDER BY " + orderBy;
    }

    if (limit > 0) {
        sql += QString(" LIMIT %1").arg(limit);
    }

    sql += ";";
    return sql;
}

/**
 * @brief 对WHERE条件中的字符串值进行SQL注入防护
 * 仅转义单引号，防止闭合字符串引发的注入
 */
QString SqlGenerator::sanitizeCondition(const QString& condition)
{
    if (condition.isEmpty()) return "";

    QString sanitized = condition;
    // 匹配单引号包裹的值并转义其中的单引号
    QRegExp valueRegex("'([^']*)'");
    int pos = 0;

    while ((pos = valueRegex.indexIn(sanitized, pos)) != -1) {
        QString value = valueRegex.cap(1);
        // 仅将单引号转义为两个单引号
        QString escapedValue = value.replace("'", "''");
        sanitized.replace(pos + 1, value.length(), escapedValue);
        pos += valueRegex.matchedLength() + (escapedValue.length() - value.length());
    }

    return sanitized;
}
